package com.lineage.data.npc;

import com.lineage.DatabaseFactory;
import com.lineage.config.ConfigOther;
import com.lineage.server.IdFactory;
import com.lineage.server.datatables.NpcTable;
import com.lineage.server.model.Instance.L1MonsterInstance;
import com.lineage.server.model.Instance.L1NpcInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.L1Inventory;
import com.lineage.server.model.L1Object;
import com.lineage.server.model.L1Teleport;
import com.lineage.server.serverpackets.S_BlueMessage;
import com.lineage.server.serverpackets.S_CharVisualUpdate;
import com.lineage.server.serverpackets.S_MapID;
import com.lineage.server.serverpackets.S_OtherCharPacks;
import com.lineage.server.serverpackets.S_OwnCharPack;
import com.lineage.server.serverpackets.S_RemoveObject;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.S_SystemMessage;
import com.lineage.server.serverpackets.S_Weather;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.utils.RandomArrayList;
import com.lineage.server.utils.SQLUtil;
import com.lineage.server.world.World;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

public class TextTask {
  private static final int _minPlayer = ConfigOther.TextMinPlayer;
  
  private static final int _maxPlayer = ConfigOther.TextMaxPlayer;
  
  private static final int _level = ConfigOther.TextLevel;
  
  private static final int _bossId1 = ConfigOther.Textnpa1;
  
  private static final int _bossId2 = ConfigOther.Textnpa2;
  
  private static final int _bossId3 = ConfigOther.Textnpa3;
  
  private static final int _bossId4 = ConfigOther.Textnpa4;
  
  private static final int _bossId5 = ConfigOther.Textnpa5;
  
  private static final int _bossId6 = ConfigOther.Textnpa6;
  
  private static final int _bossId7 = ConfigOther.Textnpa7;
  
  private static final int _bossId8 = ConfigOther.Textnpa8;
  
  private static final int _bossId9 = ConfigOther.Textnpa9;
  
  private static final int _bossId10 = ConfigOther.Textnpa10;
  
  private static final int _adena = ConfigOther.TextMoney;
  
  private final ArrayList<L1PcInstance> _members = new ArrayList<>();
  
  protected L1NpcInstance _targetNpc = null;
  
  private int _TextTaskStatus = 0;
  
  private static TextTask _instance;
  
  public static final int STATUS_NONE = 0;
  
  public static final int STATUS_READY = 1;
  
  public static final int STATUS_PLAYING = 2;
  
  public static final int STATUS_CLEANING = 4;
  
  public static TextTask getInstance() {
    if (_instance == null)
      _instance = new TextTask(); 
    return _instance;
  }
  
  public String enterTextTask(L1PcInstance pc) {
    if (pc.getLevel() < _level && !isMember(pc)) {
      pc.sendPackets((ServerBasePacket)new S_SystemMessage("你的等级不足，无法挑战Boss武道馆。"));
      return "";
    } 
    if (pc.getQuest().get_step(90558) == 1 && pc.getQuest().get_step(90559) == 0) {
      pc.sendPackets((ServerBasePacket)new S_SystemMessage("您已经执行过上限1次。"));
      return "";
    } 
    if (pc.getQuest().get_step(90558) == 1 && pc.getQuest().get_step(90559) == 2) {
      pc.sendPackets((ServerBasePacket)new S_SystemMessage("您今日无法在进入武道馆了。"));
      return "";
    } 
    if (getInstance().getTextTaskStatus() == 4) {
      pc.sendPackets((ServerBasePacket)new S_SystemMessage("目前Boss武道馆的场地正在清洁中。"));
      return "";
    } 
    if (getInstance().getTextTaskStatus() == 2) {
      pc.sendPackets((ServerBasePacket)new S_ServerMessage(1182));
      return "";
    } 
    if (getMembersCount() >= _maxPlayer && !isMember(pc)) {
      pc.sendPackets((ServerBasePacket)new S_SystemMessage("Boss武道馆人数已满，下次请早。"));
      return "";
    } 
    if (!pc.getInventory().checkItem(ConfigOther.tcheckitem, _adena)) {
      pc.sendPackets((ServerBasePacket)new S_ServerMessage(189));
      return "";
    } 
    if ((pc.getInventory().checkItem(40089, 1L) || pc.getInventory().checkItem(140089, 1L)) && !isMember(pc)) {
      pc.sendPackets((ServerBasePacket)new S_SystemMessage("请把复活卷轴给删除，不然不给进入场地。"));
      return "";
    } 
    L1Teleport.teleport(pc, 32701, 32894, (short)97, pc.getHeading(), true);
    addMember(pc);
    return "";
  }
  
  private void addMember(L1PcInstance pc) {
    if (!this._members.contains(pc)) {
      this._members.add(pc);
      pc.getInventory().consumeItem(ConfigOther.tcheckitem, _adena);
    } 
    if (getMembersCount() == ConfigOther.TextMinPlayer && getTextTaskStatus() == 0) {
      GeneralThreadPool.get().execute(new runTextTask());
      L1PcInstance[] membersArray;
      int length = (membersArray = getMembersArray()).length;
      int i = 0;
      while (i < length) {
        L1PcInstance pc2 = membersArray[i];
        if (pc2.getMapId() == 97)
          pc2.sendPackets((ServerBasePacket)new S_SystemMessage("怪物强度-[简单强度]。")); 
        i++;
      } 
    } 
  }
  
  private boolean checkPlayerCount() {
    if (getMembersCount() < _minPlayer) {
      setTextTaskStatus(4);
      sendMessage("人数不足 " + _minPlayer + " 人，所以强制关闭游戏");
      L1PcInstance[] membersArray;
      int length = (membersArray = getMembersArray()).length;
      int i = 0;
      while (i < length) {
        L1PcInstance pc = membersArray[i];
        pc.getInventory().storeItem(ConfigOther.tcheckitem, _adena);
        pc.sendPackets((ServerBasePacket)new S_SystemMessage("退还金币(" + _adena + ")。"));
        L1Teleport.teleport(pc, 33442, 32797, (short)4, pc.getHeading(), true);
        i++;
      } 
      clearMembers();
      return false;
    } 
    return true;
  }
  
  private void endTextTask1() {
    setTextTaskStatus(4);
    sendMessage("Boss武道馆挑战失败.请下次再来!!");
    L1PcInstance[] membersArray;
    int length = (membersArray = getMembersArray()).length;
    int i = 0;
    while (i < length) {
      L1PcInstance pc = membersArray[i];
      if (pc.getMapId() == 97)
        L1Teleport.teleport(pc, 33442, 32797, (short)4, pc.getHeading(), true); 
      i++;
    } 
    clearMembers();
    clearColosseum();
  }
  
  private void endTextTask() {
    setTextTaskStatus(4);
    sendMessage("Boss武道馆时间到了.请下次再来挑战!!");
    L1PcInstance[] membersArray;
    int length = (membersArray = getMembersArray()).length;
    int i = 0;
    while (i < length) {
      L1PcInstance pc = membersArray[i];
      if (pc.getMapId() == 97)
        L1Teleport.teleport(pc, 33442, 32797, (short)4, pc.getHeading(), true); 
      if (pc.isDead())
        restartPlayer(pc, 32616, 32782, (short)4); 
      i++;
    } 
    clearMembers();
    clearColosseum();
  }
  
  public void restartPlayer(L1PcInstance pc, int locx, int locy, short mapid) {
    pc.removeAllKnownObjects();
    pc.broadcastPacketAll((ServerBasePacket)new S_RemoveObject((L1Object)pc));
    pc.setCurrentHp(pc.getLevel());
    pc.set_food(40);
    pc.setDead(false);
    pc.setStatus(0);
    World.get().moveVisibleObject((L1Object)pc, mapid);
    pc.setX(locx);
    pc.setY(locy);
    pc.setMap(mapid);
    pc.sendPackets((ServerBasePacket)new S_MapID(pc, pc.getMapId(), pc.getMap().isUnderwater()));
    pc.broadcastPacketAll((ServerBasePacket)new S_OtherCharPacks(pc));
    pc.sendPackets((ServerBasePacket)new S_OwnCharPack(pc));
    pc.sendPackets((ServerBasePacket)new S_CharVisualUpdate(pc));
    pc.startHpRegeneration();
    pc.startMpRegeneration();
    pc.sendPackets((ServerBasePacket)new S_Weather(World.get().getWeather()));
    pc.stopPcDeleteTimer();
    if (pc.getHellTime() > 0)
      pc.beginHell(false); 
    pc.sendPackets((ServerBasePacket)new S_SystemMessage("强制退出地图,请自行登出重新进入游戏即可!!"));
  }
  
  private void clearColosseum() {
    Iterator<L1Object> iterator = World.get().getVisibleObjects(97).values().iterator();
    while (iterator.hasNext()) {
      Object obj = iterator.next();
      if (obj instanceof L1MonsterInstance) {
        L1MonsterInstance mob = (L1MonsterInstance)obj;
        if (mob.isDead())
          continue; 
        mob.setDead(true);
        mob.setStatus(8);
        mob.setCurrentHpDirect(0);
        mob.deleteMe();
        continue;
      } 
      if (!(obj instanceof L1Inventory))
        continue; 
      L1Inventory inventory = (L1Inventory)obj;
      inventory.clearItems();
    } 
  }
  
  private void spawnBoss(int npcid, String msg1, String msg2) {
    if (msg1.equalsIgnoreCase("9")) {
      sendMessage("第 " + msg1 + " 关 [" + getBossName(npcid) + "] 120秒后开始第 " + msg2 + " 关");
    } else if (msg1.equalsIgnoreCase("10")) {
      sendMessage("最后一关 [" + getBossName(npcid) + "] 请努力撑下去");
    } else {
      sendMessage("第 " + msg1 + " 关 [" + getBossName(npcid) + "] 60秒后开始第 " + msg2 + " 关");
    } 
    spawn(npcid);
  }
  
  private void spawn(int npcid) {
    try {
      L1NpcInstance npc = NpcTable.get().newNpcInstance(npcid);
      npc.setId(IdFactory.get().nextId());
      npc.setMap((short)97);
      npc.setX(32701 + RandomArrayList.getInt(5));
      npc.setY(32894 + RandomArrayList.getInt(5));
      Thread.sleep(1L);
      npc.setHomeX(npc.getX());
      npc.setHomeY(npc.getY());
      npc.setHeading(4);
      World.get().storeObject((L1Object)npc);
      World.get().addVisibleObject((L1Object)npc);
      npc.turnOnOffLight();
      npc.startChat(0);
    } catch (Exception exception) {}
  }
  
  private String getBossName(int npcId) {
    String BossName = null;
    Connection con = null;
    PreparedStatement pstm = null;
    ResultSet rs = null;
    try {
      con = DatabaseFactory.get().getConnection();
      pstm = con.prepareStatement("select name from npc where npcid = ?");
      pstm.setInt(1, npcId);
      rs = pstm.executeQuery();
      if (rs.next())
        BossName = rs.getString("name"); 
    } catch (SQLException sQLException) {
    
    } finally {
      SQLUtil.close(rs, pstm, con);
    } 
    return BossName;
  }
  
  private void sendMessage(String msg) {
    L1PcInstance[] membersArray;
    int length = (membersArray = getMembersArray()).length;
    int i = 0;
    while (i < length) {
      L1PcInstance pc = membersArray[i];
      if (pc.getMapId() == 97)
        pc.sendPackets((ServerBasePacket)new S_BlueMessage(166, "\\f3" + msg)); 
      i++;
    } 
  }
  
  private void setTextTaskStatus(int i) {
    this._TextTaskStatus = i;
  }
  
  private int getTextTaskStatus() {
    return this._TextTaskStatus;
  }
  
  private void clearMembers() {
    this._members.clear();
  }
  
  private boolean isMember(L1PcInstance pc) {
    return this._members.contains(pc);
  }
  
  private L1PcInstance[] getMembersArray() {
    return this._members.<L1PcInstance>toArray(new L1PcInstance[this._members.size()]);
  }
  
  private int getMembersCount() {
    return this._members.size();
  }
  
  private class runTextTask implements Runnable {
    private runTextTask() {}
    
    public void run() {
      try {
        TextTask.this.sendMessage("Boss武道馆即将开始，请勿离开场地或登出。");
        Thread.sleep(10000L);
        TextTask.this.setTextTaskStatus(1);
        TextTask.this.sendMessage("60秒后开始游戏");
        Thread.sleep(55000L);
        TextTask.this.sendMessage("倒数5秒");
        Thread.sleep(1000L);
        TextTask.this.sendMessage("4秒");
        Thread.sleep(1000L);
        TextTask.this.sendMessage("3秒");
        Thread.sleep(1000L);
        TextTask.this.sendMessage("2秒");
        Thread.sleep(1000L);
        TextTask.this.sendMessage("1秒");
        Thread.sleep(1000L);
        if (TextTask.this.checkPlayerCount()) {
          TextTask.this.sendMessage("Boss武道馆怪物即将登场。愿上帝保佑你！");
          TextTask.this.setTextTaskStatus(2);
          L1PcInstance[] access$3;
          int length = (access$3 = TextTask.this.getMembersArray()).length;
          int i = 0;
          while (i < length) {
            L1PcInstance pc1 = access$3[i];
            if (pc1.getMapId() == 97) {
              pc1.getQuest().set_step(90558, 1);
              if (pc1.getQuest().get_step(90559) == 1)
                pc1.getQuest().set_step(90559, 2); 
            } 
            i++;
          } 
          TextTask.this.spawnBoss(TextTask._bossId1, "1", "2");
          Thread.sleep(60000L);
          TextTask.this.spawnBoss(TextTask._bossId2, "2", "3");
          Thread.sleep(60000L);
          TextTask.this.spawnBoss(TextTask._bossId3, "3", "4");
          Thread.sleep(60000L);
          TextTask.this.spawnBoss(TextTask._bossId4, "4", "5");
          Thread.sleep(60000L);
          TextTask.this.spawnBoss(TextTask._bossId5, "5", "6");
          Thread.sleep(60000L);
          TextTask.this.spawnBoss(TextTask._bossId6, "6", "7");
          Thread.sleep(60000L);
          TextTask.this.spawnBoss(TextTask._bossId7, "7", "8");
          Thread.sleep(60000L);
          TextTask.this.spawnBoss(TextTask._bossId8, "8", "9");
          Thread.sleep(60000L);
          TextTask.this.spawnBoss(TextTask._bossId9, "9", "10");
          Thread.sleep(120000L);
          TextTask.this.spawnBoss(TextTask._bossId10, "10", null);
          Thread.sleep(180000L);
          TextTask.this.endTextTask();
        } 
        Thread.sleep(5000L);
        TextTask.this.setTextTaskStatus(0);
      } catch (InterruptedException e) {
        e.printStackTrace();
      } 
    }
  }
}
